#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "util.h"
#include "rtp.h"

#define SEND_BUFFER_SIZE (PKT_SIZE * MAX_WINDOWS)

int sender(char *receiver_ip, char *receiver_port, int window_size, char *message)
{

	// create receiver address
	struct sockaddr_in receiver_addr;
	memset(&receiver_addr, 0, sizeof(receiver_addr));
	receiver_addr.sin_family = AF_INET;
	receiver_addr.sin_port = htons(atoi(receiver_port));

	// create socket
	int sock = 0;
	if ((sock = rtp_socket(window_size, &receiver_addr)) < 0)
	{
		perror("socket failed");
		exit(EXIT_FAILURE);
	}

	// convert IPv4 or IPv6 addresses from text to binary form
	if (inet_pton(AF_INET, receiver_ip, &receiver_addr.sin_addr) <= 0)
	{
		perror("address failed");
		exit(EXIT_FAILURE);
	}

	// connect to server
	if (rtp_connect(sock, (struct sockaddr *)&receiver_addr, sizeof(struct sockaddr)) >= 0)
		puts("[INFO] : Connect successful!");
	else
	{
		puts("[INFO] : Connect Failed.");
		close(sock);
		return 0;
	}
	// send data
	// char test_data[] = "Hello, world!\n";

	// TODO: if message is filename, open the file and send its content

	char data[SEND_BUFFER_SIZE];
	char filename[128];
	// strcpy(filename, "../data/");
	strcpy(filename, message);
	FILE *fp = fopen(filename, "r");
	if (fp == NULL)
	{
		rtp_sendto_opt(sock, (void *)message, strlen(message), 0, (struct sockaddr *)&receiver_addr, sizeof(struct sockaddr));
	}
	else
	{
		for (size_t read_bytes = fread(data, 1, SEND_BUFFER_SIZE, fp); read_bytes > 0; read_bytes = fread(data, 1, SEND_BUFFER_SIZE, fp))
			rtp_sendto_opt(sock, (void *)data, read_bytes, 0, (struct sockaddr *)&receiver_addr, sizeof(struct sockaddr));
	}
	// close rtp socket
	rtp_close_sender(sock);

	return 0;
}

/*
 * main()
 * Parse command-line arguments and call sender function
 */
int main(int argc, char **argv)
{
	char *receiver_ip;
	char *receiver_port;
	int window_size;
	char *message;

	if (argc != 5)
	{
		fprintf(stderr, "Usage: ./sender [Receiver IP] [Receiver Port] [Window Size] [message]");
		exit(EXIT_FAILURE);
	}

	receiver_ip = argv[1];
	receiver_port = argv[2];
	window_size = atoi(argv[3]);
	message = argv[4];
	return sender(receiver_ip, receiver_port, window_size, message);
}